/**
 * @(#)TaskInstanceOutComes.java Nov 27, 2009
 *   
 * Copyright  (c) 2009-2010 Wilmar IT Service,  Inc.   
 * All  rights  reserved.   
 * TODO
 */

package com.wilmar.process.web.taglibs;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.servlet.jsp.JspWriter;

import org.apache.log4j.Logger;
import org.jbpm.api.JbpmException;

import com.wilmar.process.core.ProcessSystemDeclareKeys;
import com.wilmar.process.core.services.api.ISystemTaskInstanceService;
import com.wilmar.process.enumerate.EnumProcessBeanIdSet;
import com.wilmar.process.enumerate.EnumProcessSystemTagFixedVariableNameSet;
import com.wilmar.process.enumerate.EnumProcessTagSupportPublicAttribute;
import com.wilmar.process.enumerate.EnumTagLibParameterScope;
import com.wilmar.process.enumerate.EnumTagLibResource;
import com.wilmar.process.exception.NoUserSessionException;

/**
 * @author MaKuBEX Email:makubexnet@gmail.com
 * @version 1.0.0
 */
public class TaskInstanceOutComesTag extends ProcessTagSupport {

	/**
	 * @serialField
	 */
	private static final long serialVersionUID = 2611678785351962245L;
	private static final Logger log = Logger.getLogger
			(TaskInstanceOutComesTag.class);

	public static final String OUT_COMES_LAYOUT_BUTTON = "button";
	public static final String OUT_COMES_LAYOUT_RADIO = "radio";

	private static final String DEFAULT_RADIO_BUTTON_NAME = "taskinstance_form_radio";

	private String formid;
	private String formaction;
	private String filter;
	private String layout;

	/**
	 * @see org.springframework.web.servlet.tags.RequestContextAwareTag#doStartTagInternal()
	 */
	protected int doStartTagInternal() throws Exception {
		String currentTaskInstanceId = null;
		ISystemTaskInstanceService systemTaskInstanceService = (ISystemTaskInstanceService) super
				.getBean(EnumProcessBeanIdSet.PROCESS_SYSTEM_TASKINSTANCE_SERVICE);
		if (super.taskInstanceId != null
				&& super.taskInstanceId.trim().length() != 0)
			currentTaskInstanceId = super.taskInstanceId;
		try {
			if (currentTaskInstanceId == null)
				currentTaskInstanceId = super
						.getAttribute(EnumProcessSystemTagFixedVariableNameSet.PROCESS_INFORMATION_TASK_INSTANCE_ID);
		} catch (Exception e) {
			log
					.warn("Could not find the value of the task instance id, now try to find it in task instance!");
			throw e;
		}
		Set<String> outComeSet = null;
		try {
			outComeSet = systemTaskInstanceService
					.getOutComes(currentTaskInstanceId);
		} catch (JbpmException e) {
			currentTaskInstanceId = super
					.getAttribute(
							EnumProcessSystemTagFixedVariableNameSet.PROCESS_INFORMATION_TASK_INSTANCE_ID,
							EnumTagLibParameterScope.REQUEST_ATTRIBUTE);
			outComeSet = systemTaskInstanceService
					.getOutComes(currentTaskInstanceId);
		}
		List<String> outComeList = new ArrayList<String>(outComeSet);
		Collections.sort(outComeList);
		StringBuffer html = null;
		if (this.layout != null
				&& this.layout.equalsIgnoreCase(OUT_COMES_LAYOUT_RADIO)) {
			html = this.generateRadioCode(outComeList);
		} else {
			html = this.generateButtonCode(outComeList);
		}
		JspWriter outer = this.getOut();
		outer.write(html.toString());
		return SKIP_BODY;
	}

	private StringBuffer generateRadioCode(List<String> outComeList)
			throws NoUserSessionException {
		StringBuffer html = new StringBuffer();
		for (String outCome : outComeList) {
			if (this.filter != null && this.filter.contains(outCome))
				continue;
			html.append("<input type=\"radio\" value=\"");
			html.append(outCome);
			html.append("\" ");
			super.appendPublicAttribute(html,
					EnumProcessTagSupportPublicAttribute.CSSCLASS);
			super.appendPublicAttribute(html,
					EnumProcessTagSupportPublicAttribute.CSSSTYLE);
			html.append(" onclick=\"doCopyOutcome(");
			html.append("'" + outCome + "'");
			html.append(");\" />");
			html.append(outCome + "&nbsp;");
		}
		html.append("\n");
		html.append("<center>");
		html.append("<input type=\"submit\" name=\"");
		html.append(DEFAULT_RADIO_BUTTON_NAME);
		html.append(" value=\"");
		html.append(super
				.getText(EnumTagLibResource.TASKINSTANCE_FORM_SUBMIT_BUTTON));
		html.append("\" onclick=\"");
		if (super.onsubmit != null && super.onsubmit.trim().length() > 0) {
			if (!super.onsubmit.endsWith(";"))
				super.onsubmit = super.onsubmit + ";";
			html.append(super.onsubmit);
		}
		html.append("doCopyOpinion();doSubmitForm(");
		if (this.formaction != null && this.formaction.trim().length() != 0) {
			html.append("'" + this.formaction + "'");
		}
		if (this.formid != null && this.formid.trim().length() != 0) {
			if (this.formaction != null && this.formaction.trim().length() != 0) {
				html.append(",");
			}
			html.append("'" + this.formid + "'");
		}
		html.append(");\"/>");
		html.append("</center>");
		return html;
	}

	private StringBuffer generateButtonCode(List<String> outComeList) {
		StringBuffer html = new StringBuffer();
		html.append("<span id=\""
				+ ProcessSystemDeclareKeys.TASKINSTANCE_FORM_COMMIT_BUTTON_DIV
				+ "\">");
		for (String outCome : outComeList) {
			if (this.filter != null && this.filter.contains(outCome))
				continue;
			html
					.append("<input type=\"button\" id=\""
							+ ProcessSystemDeclareKeys.TASKINSTANCE_FORM_COMMIT_BUTTON_ID_PREFIX
							+ outCome + "\" value=\"");
			html.append(outCome);
			html.append("\" ");
			super.appendPublicAttribute(html,
					EnumProcessTagSupportPublicAttribute.CSSCLASS);
			super.appendPublicAttribute(html,
					EnumProcessTagSupportPublicAttribute.CSSSTYLE);
			html.append(" onclick=\"");
			if (super.onsubmit != null && super.onsubmit.trim().length() > 0) {
				if (!super.onsubmit.endsWith(";"))
					super.onsubmit = super.onsubmit + ";";
				html.append(super.onsubmit);
			}
			html.append("doCopyOpinion();return doCompleteTask(");
			html.append("'" + outCome + "'");
			if (this.formaction != null && this.formaction.trim().length() != 0) {
				html.append(",'" + this.formaction + "'");
			}
			if (this.formid != null && this.formid.trim().length() != 0) {
				html.append(",'" + this.formid + "'");
			}
			html.append(");\"/>");
			html.append("&nbsp;");
		}
		html.append("</span>");
		return html;
	}

	/**
	 * @return the formid
	 */
	public String getFormid() {
		return formid;
	}

	/**
	 * @param formid
	 *            the formid to set
	 */
	public void setFormid(String formid) {
		this.formid = formid;
	}

	/**
	 * @return the formaction
	 */
	public String getFormaction() {
		return formaction;
	}

	/**
	 * @param formaction
	 *            the formaction to set
	 */
	public void setFormaction(String formaction) {
		this.formaction = formaction;
	}

	/**
	 * @return the filter
	 */
	public String getFilter() {
		return filter;
	}

	/**
	 * @param filter
	 *            the filter to set
	 */
	public void setFilter(String filter) {
		this.filter = filter;
	}

	/**
	 * @return the layout
	 */
	public String getLayout() {
		return layout;
	}

	/**
	 * @param layout
	 *            the layout to set
	 */
	public void setLayout(String layout) {
		this.layout = layout;
	}

}
